<template>
  <div class="drugs">
    <div class="drugs-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-drugsadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1">
          <!-- 导入 -->
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button type="primary" v-btnpermission="'btn-drugsload'"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="类型">
            <el-radio-group v-model="formSearch.Type">
              <el-radio :label="1">药品</el-radio>
              <el-radio :label="2">耗材</el-radio>
              <el-radio :label="3">设备</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="formSearch.Name" />
          </el-form-item>
          <el-form-item prop="DrugsType" label="药品分类">
            <el-select
              v-model="formSearch.DrugsType"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in DrugsTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="GivenPerson" label="适用对象">
            <el-select
              v-model="formSearch.GivenPerson"
              placeholder="--请选择--"
              clearable
              filterable
            >
              <el-option
                v-for="item in GivenPersonOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="drugs-list">
      <el-row>
        <el-col>
          <!-- 角色列表 -->
          <el-table :data="drugsList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column prop="Name" label="名称"></el-table-column>
            <el-table-column prop="Name" label="是否含兴奋剂">
              <template #default="{ row }">
                <el-tag :type="row.IsContainDope == 1 ? 'danger' : ''">
                  {{ row.IsContainDope == 1 ? '有' : '无' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="typeName" label="类型"></el-table-column>
            <el-table-column
              prop="givenPersonName"
              label="给要人群"
            ></el-table-column>
            <el-table-column
              prop="drugsTypeName"
              label="用药方式"
            ></el-table-column>
            <el-table-column
              prop="Specifications"
              label="规格"
            ></el-table-column>
            <el-table-column prop="unitName" label="单位"></el-table-column>
            <el-table-column prop="IsValid" label="是否有效">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.IsValid"
                  :active-value="1"
                  :inactive-value="0"
                  disabled
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-drugsupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-drugsdelete'"
                  @click="rowDelete(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <el-dialog
        title="新增药品"
        v-model="addDialogVisible"
        width="20%"
        @close="addDislogClosed"
      >
        <el-form
          :model="addDialogForm"
          :rules="drugsFormRulesMixin.addFormRules"
          ref="addDialogRef"
          label-width="80px"
          inline
        >
          <el-form-item label="名称" prop="Name">
            <el-input v-model="addDialogForm.Name" />
          </el-form-item>
          <el-form-item label="类型" prop="Type">
            <el-radio-group v-model="addDialogForm.Type">
              <el-radio :label="1">药品</el-radio>
              <el-radio :label="2">耗材</el-radio>
              <el-radio :label="3">设备</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否有效" prop="IsValid">
            <el-checkbox
              v-model="addDialogForm.IsValid"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item label="含兴奋剂" prop="IsContainDope">
            <el-checkbox
              v-model="addDialogForm.IsContainDope"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item prop="Unit" label="单位">
            <el-select v-model="addDialogForm.Unit" placeholder="--请选择--">
              <el-option
                v-for="item in unitOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="Specifications" label="规格">
            <el-input v-model="addDialogForm.Specifications" />
          </el-form-item>
          <el-form-item prop="DrugsType" label="给药方式">
            <el-select
              v-model="addDialogForm.DrugsType"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in DrugsTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="GivenPerson" label="给药人群">
            <el-select
              v-model="addDialogForm.GivenPerson"
              placeholder="--请选择--"
              multiple
            >
              <el-option
                v-for="item in GivenPersonOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="顺序" prop="SN">
            <el-input-number v-model="addDialogForm.SN" />
          </el-form-item>
          <el-form-item label="备注" prop="Remarks">
            <el-input v-model="addDialogForm.Remarks" />
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
      <el-dialog
        title="编辑人员"
        v-model="editDialogVisible"
        width="20%"
        @close="editDislogClosed"
      >
        <el-form
          :model="editDialogForm"
          :rules="drugsFormRulesMixin.editFormRules"
          ref="editDialogRef"
          label-width="80px"
          inline
        >
          <el-form-item label="名称" prop="Name">
            <el-input v-model="editDialogForm.Name" />
          </el-form-item>
          <el-form-item label="类型" prop="Type">
            <el-radio-group v-model="editDialogForm.Type">
              <el-radio :label="1">药品</el-radio>
              <el-radio :label="2">耗材</el-radio>
              <el-radio :label="3">设备</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否有效" prop="IsValid">
            <el-checkbox
              v-model="editDialogForm.IsValid"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item label="含兴奋剂" prop="IsContainDope">
            <el-checkbox
              v-model="editDialogForm.IsContainDope"
              :true-label="1"
              :false-label="0"
            />
          </el-form-item>
          <el-form-item prop="Unit" label="单位">
            <el-select v-model="editDialogForm.Unit" placeholder="--请选择--">
              <el-option
                v-for="item in unitOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="Specifications" label="规格">
            <el-input v-model="editDialogForm.Specifications" />
          </el-form-item>
          <el-form-item prop="DrugsType" label="给药方式">
            <el-select
              v-model="editDialogForm.DrugsType"
              placeholder="--请选择--"
            >
              <el-option
                v-for="item in DrugsTypeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="GivenPerson" label="给药人群">
            <el-select
              v-model="editDialogForm.GivenPerson"
              placeholder="--请选择--"
              multiple
            >
              <el-option
                v-for="item in GivenPersonOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="顺序" prop="SN">
            <el-input-number v-model="editDialogForm.SN" />
          </el-form-item>
          <el-form-item label="备注" prop="Remarks">
            <el-input v-model="editDialogForm.Remarks" />
          </el-form-item>
        </el-form>
        <template v-slot:footer>
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFormSubmit">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { drugsFormRulesMixin } from '@/utils/mixin.js';
import {
  getDrugsList,
  addDrugs,
  editDrugs,
  delDrugs,
  addDrugsList,
} from '@/network/drugs.js';
import { ref, reactive, onBeforeMount } from 'vue';
import { getDicByDictionary } from '@/network/dictionary.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';
import { importExcel } from '@/utils/excel';

//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
// 搜索条件
const formSearch = reactive({
  GivenPerson: '',
  DrugsType: '',
  Name: '',
  Type: 1,
  total: 0,
  page: 1,
  pageSize: 10,
});
//初始化
let drugsList = ref(null);
const initData = async () => {
  let params = {
    Name: formSearch.Name,
    Type: formSearch.Type,
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    GivenPerson: formSearch.GivenPerson,
    DrugsType: formSearch.DrugsType,
  };
  await getDrugsList(params).then((res) => {
    drugsList.value = res.data;
    formSearch.total = res.total;
    console.info(res, '提交搜索数据');
  });
};
//初始化字典
const unitOption = ref([]);
const DrugsTypeOption = ref([]);
const GivenPersonOption = ref([]);
const initDict = async () => {
  await getDicByDictionary({ type: 'UnitType' }).then((res) => {
    unitOption.value = res;
  });
  await getDicByDictionary({ type: 'DrugsType' }).then((res) => {
    DrugsTypeOption.value = res;
  });
  await getDicByDictionary({ type: 'PantientType' }).then((res) => {
    GivenPersonOption.value = res;
  });
};
onBeforeMount(() => {
  initData();
  initDict();
});
//新增
const addDialogVisible = ref(false);
const addDialogRef = ref(null);
const addDialogForm = ref({
  Name: '',
  Type: 1,
  Unit: '',
  IsValid: 1,
  SN: 0,
  Remarks: '',
  DrugsType: null,
  Specifications: null,
  GivenPerson: null,
  IsContainDope: '',
});
const addFormSubmit = async () => {
  await addDialogRef.value.validate(async (valid) => {
    if (valid) {
      addDialogForm.value.GivenPerson =
        addDialogForm.value.GivenPerson &&
        addDialogForm.value.GivenPerson.toString();
      await addDrugs(addDialogForm.value)
        .then(() => {
          addDialogVisible.value = false;
          initData();
          initDict();
          ElMessage.success('新增成功');
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
const addDislogClosed = () => {
  // addDialogForm.value = {};
  addDialogRef.value.resetFields();
  addDialogRef.value.clearValidate();
};
//编辑
const editDialogVisible = ref(false);
const editDialogRef = ref(null);
let editDialogForm = ref({
  Code: 0,
  Name: '',
  Type: 1,
  Unit: '',
  IsValid: 1,
  SN: 0,
  Remarks: '',
  DrugsType: null,
  Specifications: null,
  GivenPerson: null,
  IsContainDope: '',
});
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  editDialogForm.value = JSON.parse(JSON.stringify(row));
  editDialogForm.value.GivenPerson =
    editDialogForm.value.GivenPerson &&
    editDialogForm.value.GivenPerson.split(',');
};
const editDislogClosed = () => {
  editDialogForm.value = {};
};
const editFormSubmit = async () => {
  await editDialogRef.value.validate(async (valid) => {
    if (valid) {
      editDialogForm.value.GivenPerson =
        editDialogForm.value.GivenPerson &&
        editDialogForm.value.GivenPerson.toString();
      await editDrugs(editDialogForm.value)
        .then(() => {
          editDialogVisible.value = false;
          initData();
          // initDict();
          ElMessage.success('编辑成功');
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      ElMessage.error('请按要求填写');
      return false;
    }
  });
};
//删除
const rowDelete = async (id) => {
  await ElMessageBox.confirm('确定删除该条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async (action) => {
    if (action === 'confirm') {
      await delDrugs({ code: id })
        .then(() => {
          initData();
          // initDict();
          ElMessage.success('删除成功');
        })
        .catch((err) => {
          console.log(err);
          ElMessage.success('删除失败');
        });
    }
  });
};
//搜索
const onSubmit = async () => {
  formSearch.page = 1;
  await initData();
};
//重置
const onReset = async () => {
  formSearch.Name = '';
  // formSearch.Type = "";
  formSearch.Code = '';
  formSearch.GuaranteeType = '';
  formSearch.DrugsType = '';
  formSearch.page = 1;
  await initData();
};
//分页
const handleCurrentChange = async (val) => {
  formSearch.page = val;
  await initData();
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addDrugsList(res)
        .then(() => {
          ElMessage.success('导入成功');
          initDict();
          initData();
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('导入失败');
        });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
</script>

<style lang="scss" scoped>
.drugs {
  margin: 14px 15px 14px;
  .drugs-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .drugs-list {
    margin-top: 14px;
  }
}
</style>
